package com.itheima.freemark.controller;

import com.itheima.freemark.entity.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * @author 陈辉
 * @data 2023 11:15
 */
@RestController
public class FreemarkController {

    @Autowired
    private Configuration configuration;

    @GetMapping("/fmDemo")
    public String process() throws Exception {
        //1. 拿到要填充模板的数据
        List<Student> list = getData();
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("stus",list);
        //2. 拿到要填充的模板
        Template template = configuration.getTemplate("02-list.ftl");
        //3. 将数据填充到指定模板  -- 合成完整页面
        template.process(dataMap,new FileWriter("D:\\IdeaProjects\\heima-leadnews\\heima-leadnews-test\\freemark-demo\\src\\main\\resources\\pages\\02-list.html"));

        //返回结果
        return "ok";
    }

    private List<Student> getData() {
        Student stu1 = new Student();
        stu1.setName("小强");
        stu1.setAge(18);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());

        //小红对象模型数据
        Student stu2 = new Student();
        stu2.setName("小红");
        stu2.setMoney(200.1f);
        stu2.setAge(19);

        //将两个对象模型数据存放到List集合中
        List<Student> stus = new ArrayList<>();
        stus.add(stu1);
        stus.add(stu2);

        return stus;
    }
}
